package qc.module.ehs.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.enums.EhsAccidentLevelEnum;
import qc.common.core.enums.EhsHazardIndentificationResultTypeEnum;
import qc.common.core.enums.EhsRiskLevelEnum;
import qc.common.core.enums.EhsTaskCategoryTypeEnum;
import qc.common.core.exception.QCPromptException;
import qc.module.ehs.dto.board.*;
import qc.module.ehs.dto.hazard.EhsHazardInfoDto;
import qc.module.ehs.dto.unit.EhsUnitDto;
import qc.module.ehs.entity.*;
import qc.module.ehs.mapper.EhsHazardInfoMapper;

import java.util.*;
import java.util.stream.Collectors;

/**
 * EhsBoardService
 * @author QuCheng Tech
 * @since 2024/12/13
 */
@Service
public class EhsBoardService {

    @Autowired
    private EhsOrgService orgService;

    @Autowired
    private EhsUnitInfoService unitInfoService;

    @Autowired
    private EhsHazardInfoService hazardInfoService;

    @Autowired
    private EhsTaskItemService taskItemService;

    @Autowired
    private EhsTroubleCorrectService troubleCorrectService;

    @Autowired
    private EhsHazardIdentifyService ehsHazardIdentifyService;

    @Autowired
    private EhsEduRecordService ehsEduRecordService;

    @Autowired
    private EhsInvestRecordService ehsInvestRecordService;

    @Autowired
    private EhsAccidentRecordService ehsAccidentRecordService;

    @Autowired
    private EhsHazardRiskevlService ehsHazardRiskevlService;

    /**
     * 获取组织最新安全状态
     * @param orgcode 组织机构代码
     * @return qc.module.ehs.dto.board.EhsBoardOrgLatestStatusDTO
     * @author QuCheng Tech
     * @since 2024/12/13
     */
    public EhsBoardOrgLatestStatusDTO getOrgLatestStatus(String orgcode) throws QCPromptException {
        EhsOrg org = orgService.getEntity(orgcode);
        if (!Objects.nonNull(org)) {
            //组织机构不存在，提示错误
            throw new QCPromptException("查询组织机构不存在");
        }
        //1.危险源信息统计：根据组织机构查询所有的危险源信息
        List<EhsHazardInfo> allHazards = hazardInfoService.getOrgAllExistHazards(orgcode, 0x0);
        //1.1第一类危险源信息
        EhsBoardHazardStsInfoDto hazard = new EhsBoardHazardStsInfoDto();
        //1.2第二类危险源信息
        EhsBoardHazardStsInfoDto trouble = new EhsBoardHazardStsInfoDto();
        //2.调用方法更新统计
        getHazardAndTroubleStatisticsInfo(allHazards, hazard, trouble);
       /* 3.风险值评估--只根据隐患进行风险评估
          3.1.单个低风险值为5，当个一般风险值为10，单个较高风险值为20，单个高风险值为40.
        */
        int hazardRisk = hazard.getBluecount() * 5 + hazard.getYellowcount() * 10 + hazard.getOrangecount() * 20 + hazard.getRedcount() * 40;
        int troubleRisk = trouble.getBluecount() * 5 + trouble.getYellowcount() * 10 + trouble.getOrangecount() * 20 + trouble.getRedcount() * 40;
        int risk = troubleRisk;
        if (risk > 100) {
            risk = 100;  // 限制 riskCount 的范围，确保其在 0 到 100 之间
        }
        //3.2.分析评估说明（0-100）超过20为低风险，超过40为一般风险，超过60为较高风险，超过80为高危风险
        String description = null;
        if (risk < 20) {
            description = "风险较低，当前状态下无需过多担忧，但仍需保持监控。";
        } else if (risk >= 20 && risk < 40) {
            description = "风险较低，问题较少，建议保持定期检查和预防。";
        } else if (risk >= 40 && risk < 60) {
            description = "风险适中，建议采取适当的防范措施，确保及时解决潜在问题。";
        } else if (risk >= 60 && risk < 80) {
            description = "风险较高，存在一定隐患，需加强监控并立即采取改进措施。";
        } else if (risk >= 80) {
            description = "风险极高，存在重大隐患，必须尽快采取紧急措施进行处理。";
        }
        //4.返回结果集
        EhsBoardOrgLatestStatusDTO ehsBoardOrgLatestStatusDTO = new EhsBoardOrgLatestStatusDTO();
        ehsBoardOrgLatestStatusDTO.setRisk(risk);
        ehsBoardOrgLatestStatusDTO.setHazard(hazard);
        ehsBoardOrgLatestStatusDTO.setTrouble(trouble);
        ehsBoardOrgLatestStatusDTO.setDescription(description);
        return ehsBoardOrgLatestStatusDTO;
    }

    /**
     * 统计指定时间段内组织的安全生产看板数据
     *
     * @param orgcode 组织机构代码
     * @return qc.module.ehs.dto.board.EhsBoardOrgLatestStatusDTO
     * @author QuCheng Tech
     * @since 2024/12/13
     */
    public EhsBoardOrgQueryResultDto queryStsOrg(String orgcode, Date beginTime, Date endTime) throws QCPromptException {
        EhsOrg org = orgService.getEntity(orgcode);
        if (!Objects.nonNull(org)) {
            //组织机构不存在，提示错误
            throw new QCPromptException("查询组织机构不存在");
        }

        //1隐患治理信息统计：根据组织机构和起止时间查询出所有隐患治理信息
        List<EhsTroubleCorrect> orgAllTroubleCorrects = troubleCorrectService.getOrgAllTroubleCorrects(orgcode, beginTime, endTime);
        //1.1隐患治理信息统计
        EhsBoardTroubleCorrectStsInfoDto troubleCorrectStsInfo = getTroubleCorrectStatisticsInfo(orgAllTroubleCorrects);

        //2任务信息统计：根据组织机构和起止时间查询出所有任务信息
        List<EhsTaskItem> allTaskItems = taskItemService.queryTaskItemEntities(orgcode, null, beginTime, endTime, -1, null);
        //2.1任务信息统计：根据组织机构和起止时间查询出所有任务项信息，在根据输入条件中传入的部门信息集合进行过滤筛选得到每个部门的任务统计信息
        EhsBoardTaskStsInfoDto allTaskStsInfo = new EhsBoardTaskStsInfoDto();//所有任务信息
        allTaskStsInfo.setCount(0x0);
        allTaskStsInfo.setFinishcount(0x0);
        allTaskStsInfo.setTimeoutfinishcount(0x0);
        EhsBoardTaskStsInfoDto taskCheckStsInfo = new EhsBoardTaskStsInfoDto();//自查类任务信息
        taskCheckStsInfo.setCount(0x0);
        taskCheckStsInfo.setFinishcount(0x0);
        taskCheckStsInfo.setTimeoutfinishcount(0x0);
        EhsBoardTaskStsInfoDto taskFacilityStsInfo = new EhsBoardTaskStsInfoDto();//设备设施类任务信息
        taskFacilityStsInfo.setCount(0x0);
        taskFacilityStsInfo.setFinishcount(0x0);
        taskFacilityStsInfo.setTimeoutfinishcount(0x0);
        EhsBoardTaskStsInfoDto taskTroubleStsInfo = new EhsBoardTaskStsInfoDto();//隐患治理类任务信息
        taskTroubleStsInfo.setCount(0x0);
        taskTroubleStsInfo.setFinishcount(0x0);
        taskTroubleStsInfo.setTimeoutfinishcount(0x0);
        EhsBoardTaskStsInfoDto taskInspectStsInfo = new EhsBoardTaskStsInfoDto();//督查类任务信息
        taskInspectStsInfo.setCount(0x0);
        taskInspectStsInfo.setFinishcount(0x0);
        taskInspectStsInfo.setTimeoutfinishcount(0x0);
        EhsBoardTaskStsInfoDto taskJobStsInfo = new EhsBoardTaskStsInfoDto();//作业活动类任务信息
        taskJobStsInfo.setCount(0x0);
        taskJobStsInfo.setFinishcount(0x0);
        taskJobStsInfo.setTimeoutfinishcount(0x0);

        if (allTaskItems != null && !allTaskItems.isEmpty()) {
            for (EhsTaskItem taskItem : allTaskItems) {
                updateAllTaskCounts(taskItem, allTaskStsInfo);//所有任务信息
                updateTaskCounts(taskItem, taskCheckStsInfo, EhsTaskCategoryTypeEnum.SECURITY_CHECK);//自查类任务信息
                updateTaskCounts(taskItem, taskFacilityStsInfo, EhsTaskCategoryTypeEnum.EQUIPMENT_MAINTENANCE);//设备设施类任务信息
                updateTaskCounts(taskItem, taskTroubleStsInfo, EhsTaskCategoryTypeEnum.HIDDEN_DANGER_CONTROL);//隐患治理类任务信息
                updateTaskCounts(taskItem, taskInspectStsInfo, EhsTaskCategoryTypeEnum.INSPECT);//督查类任务信息
                updateTaskCounts(taskItem, taskJobStsInfo, EhsTaskCategoryTypeEnum.JOB_ACTIVITY);//作业活动类任务信息
            }
        }

        //3.危险源辨识记录统计：根据组织机构和起止时间查询出所有危险源辨识统计信息
        List<EhsHazardIdentify> orgAllHazardIdentify = ehsHazardIdentifyService.queryOrgHazardIdentifyEntities(orgcode, beginTime, endTime);
        //3.1危险源辨识结果数据处理
        int identifyHazardCount = 0, reportTroubleCount = 0;
        if (orgAllHazardIdentify != null && !orgAllHazardIdentify.isEmpty()) {
            for (EhsHazardIdentify hazardIdentify : orgAllHazardIdentify) {
                if (hazardIdentify.getIdentificationresult() != null) {
                    if (hazardIdentify.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HAZARD)
                        identifyHazardCount++;//辨识危险源次数
                    if (hazardIdentify.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HIDDEN_TROUBLE)
                        reportTroubleCount++;//上报上报隐患次数
                }
            }
        }
        EhsBoardHazardIdentifyStsInfoDto identifyStsInfo = new EhsBoardHazardIdentifyStsInfoDto();
        identifyStsInfo.setHazardcount(identifyHazardCount);
        identifyStsInfo.setTroublecount(reportTroubleCount);

        //4宣传培训统计：根据组织机构和起止时间查询出所有宣传培训信息
        List<EhsEduRecord> allEduRecord = ehsEduRecordService.getAllEduRecord(orgcode, beginTime, endTime);
        //4.1宣传培训结果统计
        EhsBoardEduStsInfoDto eduStsInfo = new EhsBoardEduStsInfoDto();
        int eduCount = 0, personcout = 0, doccout = 0;//培训总次数、人次、发放资料
        Double hour = 0.0;//培训总时间
        if (allEduRecord != null && !allEduRecord.isEmpty()) {
            for (EhsEduRecord eduRecord : allEduRecord) {
                eduCount++;
                personcout += eduRecord.getPersoncount();
                doccout += eduRecord.getDoccount();
                hour += eduRecord.getHour();
            }
        }
        eduStsInfo.setCount(eduCount);
        eduStsInfo.setHour(hour);
        eduStsInfo.setDoccount(doccout);
        eduStsInfo.setPersoncount(personcout);

        //5.资金投入统计：根据组织机构和起止时间查询出所有资金投入统计信息
        List<EhsInvestRecord> allInvestRecord = ehsInvestRecordService.getAllInvestRecord(orgcode, beginTime, endTime);
        //5.1资金投入结果统计
        EhsBoardInvestStsInfoDto ehsBoardInvestStsInfoDto = new EhsBoardInvestStsInfoDto();
        Double invest = 0.0;//总金额
        if (allInvestRecord != null && !allInvestRecord.isEmpty()) {
            for (EhsInvestRecord investRecord : allInvestRecord) {
                invest += investRecord.getInvest();
            }
        }
        ehsBoardInvestStsInfoDto.setInvest(invest);

        //6.安全事故统计：根据组织机构和起止时间查询出所有安全事故统计信息
        List<EhsAccidentRecord> allAccidentRecords = ehsAccidentRecordService.queryAccidentRecordEntities(orgcode, null, beginTime, endTime);
        //6.1安全事故结果统计
        int accidentCount = 0, majorCount = 0, injurednum = 0, deathnum = 0;
        Double ecoloss = 0.0;
        if (allAccidentRecords != null && !allAccidentRecords.isEmpty()) {
            for (EhsAccidentRecord accidentRecord : allAccidentRecords) {
                accidentCount++;//次数
                injurednum += accidentRecord.getInjurednum();//重伤人数
                deathnum += accidentRecord.getDeathnum();//重大事故次数
                ecoloss += accidentRecord.getEcoloss();//直接经济损失
                if (accidentRecord.getLvl() == EhsAccidentLevelEnum.MAJOR || accidentRecord.getLvl() == EhsAccidentLevelEnum.ESPECIALLY_MAJOR)
                    majorCount++;//重大事故次数
            }
        }
        EhsBoardAccidentStsInfoDto accidentStsInfo = new EhsBoardAccidentStsInfoDto();
        accidentStsInfo.setCount(accidentCount);
        accidentStsInfo.setMajorcount(majorCount);
        accidentStsInfo.setDeathnum(deathnum);
        accidentStsInfo.setInjurednum(injurednum);
        accidentStsInfo.setEcoloss(ecoloss);

        //7.等级评价风险统计：根据组织机构和起止时间查询出所有风险评价信息
        List<EhsHazardRiskEvaluation> hazardRiskEvaluations = ehsHazardRiskevlService.geAllRiskevl(orgcode, beginTime, endTime);
        //7.1等级评价风险结果统计
        int riskEvaluationCount = 0, blueCount = 0, yellowCount = 0, orangeCount = 0, redCount = 0;
        if (hazardRiskEvaluations != null && !hazardRiskEvaluations.isEmpty()) {
            for (EhsHazardRiskEvaluation hazardRiskEvaluation : hazardRiskEvaluations) {
                riskEvaluationCount++;//总次数
                if (hazardRiskEvaluation.getRisklevel() != null) {
                    if (hazardRiskEvaluation.getRisklevel() == EhsRiskLevelEnum.LOW) blueCount++;//蓝色等级数量统计
                    if (hazardRiskEvaluation.getRisklevel() == EhsRiskLevelEnum.GENERAL) yellowCount++;//黄色等级数量统计
                    if (hazardRiskEvaluation.getRisklevel() == EhsRiskLevelEnum.GREATER) orangeCount++;//橙色等级数量统计
                    if (hazardRiskEvaluation.getRisklevel() == EhsRiskLevelEnum.MAJOR) redCount++;//红色等级数量统计
                }

            }
        }
        EhsBoardRiskEvaluationStsInfoDto riskEvaluationStsInfo = new EhsBoardRiskEvaluationStsInfoDto();
        riskEvaluationStsInfo.setCount(riskEvaluationCount);
        riskEvaluationStsInfo.setBluecount(blueCount);
        riskEvaluationStsInfo.setYellowcount(yellowCount);
        riskEvaluationStsInfo.setOrangecount(orangeCount);
        riskEvaluationStsInfo.setRedcount(redCount);

        //返回结果集
        EhsBoardOrgQueryResultDto ehsBoardOrgQueryResultDto = new EhsBoardOrgQueryResultDto();
        ehsBoardOrgQueryResultDto.setDeptid(org.getDeptid());//组织机构ID
        ehsBoardOrgQueryResultDto.setName(org.getOrgname());//组织机构名称
        ehsBoardOrgQueryResultDto.setTroublecorrect(troubleCorrectStsInfo);//隐患治理统计结果
        ehsBoardOrgQueryResultDto.setTask(allTaskStsInfo);//所有任务信息统计结果
        ehsBoardOrgQueryResultDto.setTaskcheck(taskCheckStsInfo);//自查类任务信息统计结果
        ehsBoardOrgQueryResultDto.setTaskfacility(taskFacilityStsInfo);//隐患治理类任务信息统计结果
        ehsBoardOrgQueryResultDto.setTasktrouble(taskTroubleStsInfo);//隐患治理类任务信息统计结果
        ehsBoardOrgQueryResultDto.setTaskinspect(taskInspectStsInfo);//督查类任务信息统计结果
        ehsBoardOrgQueryResultDto.setTaskjob(taskJobStsInfo);//作业活动类任务信息统计结果
        ehsBoardOrgQueryResultDto.setIdentify(identifyStsInfo);//危险源辨识统计结果
        ehsBoardOrgQueryResultDto.setEdu(eduStsInfo);//宣传培训统计结果
        ehsBoardOrgQueryResultDto.setInvest(ehsBoardInvestStsInfoDto);//资金投入统计结果
        ehsBoardOrgQueryResultDto.setRiskevl(riskEvaluationStsInfo);//风险评价统计结果
        ehsBoardOrgQueryResultDto.setAccident(accidentStsInfo);//事故统计统计结果
        return ehsBoardOrgQueryResultDto;
    }

    /**
     * 查询指定部门集合的安全生产看板数据集合
     * @param orgcode        组织机构代码
     * @param deptIdAndNames 查询的部门ID和名称键值对
     * @param beginTime      起始时间，统计任务的计划开始时间
     * @param endTime        截止时间，统计任务的计划截止时间
     * @return java.util.List<qc.module.ehs.dto.board.EhsBoardDataItemDto>
     * @author QuCheng Tech
     * @since 2024/12/13
     */
    public List<EhsBoardDataItemDto> queryChildDepts(String orgcode, HashMap<Integer, String> deptIdAndNames, Date beginTime, Date endTime) throws QCPromptException {
        //1.部门信息由输入条件传入，不需要进行处理
        // 获取下级部门ID集合
        List<Integer> deptIds = deptIdAndNames.keySet().stream().collect(Collectors.toList());
        //2.危险源信息统计：根据组织机构查询所有的危险源信息，在根据输入条件中传入的部门信息集合进行过滤筛选得到每个部门的危险源统计信息
        List<EhsHazardInfo> allHazards = hazardInfoService.getOrgAllExistHazards(orgcode, 0x0);

        //3.任务信息统计：根据组织机构和起止时间查询出所有任务项信息，在根据输入条件中传入的部门信息集合进行过滤筛选得到每个部门的任务统计信息
        List<EhsTaskItem> allTaskItems = taskItemService.queryTaskItemEntities(orgcode, null, beginTime, endTime, -1, null);

        //3.隐患治理信息统计：根据组织机构和起止时间查询出所有隐患治理信息
        List<EhsTroubleCorrect> orgAllTroubleCorrects = troubleCorrectService.getOrgAllTroubleCorrects(orgcode, beginTime, endTime);

        //4.结果处理
        List<EhsBoardDataItemDto> result = new ArrayList<>();
        for (int id : deptIds) {
            //通过部门id获取该部门的危险源集合
            List<EhsHazardInfo> hazarCollect = allHazards.stream().filter(e -> e.getResdeptid().equals(id)).collect(Collectors.toList());
            //1.1第一类危险源信息
            EhsBoardHazardStsInfoDto hazard = new EhsBoardHazardStsInfoDto();
            //1.2第二类危险源信息
            EhsBoardHazardStsInfoDto trouble = new EhsBoardHazardStsInfoDto();
            //第一、二类危险源信息统计
            getHazardAndTroubleStatisticsInfo(hazarCollect, hazard, trouble);

            //通过部门id获取该部门隐患治理统计信息集合
            List<EhsTroubleCorrect> troubleCorrect = orgAllTroubleCorrects.stream().filter(e -> e.getResdeptid().equals(id)).collect(Collectors.toList());

            //隐患治理统计数据处理
            EhsBoardTroubleCorrectStsInfoDto ehsBoardTroubleCorrectStsInfo = getTroubleCorrectStatisticsInfo(troubleCorrect);

            //通过部门id获取该部门任务集合
            List<EhsTaskItem> taskCollect = allTaskItems.stream().filter(e -> e.getResdeptid().equals(id)).collect(Collectors.toList());

            //任务信息
            EhsBoardTaskStsInfoDto task = new EhsBoardTaskStsInfoDto();//所有任务信息
            EhsBoardTaskStsInfoDto taskcheck = new EhsBoardTaskStsInfoDto();//自查类任务信息
            EhsBoardTaskStsInfoDto taskfacility = new EhsBoardTaskStsInfoDto();//设备设施类任务信息
            EhsBoardTaskStsInfoDto tasktrouble = new EhsBoardTaskStsInfoDto();//隐患治理类任务信息
            EhsBoardTaskStsInfoDto taskinspect = new EhsBoardTaskStsInfoDto();//督查类任务信息
            EhsBoardTaskStsInfoDto taskjob = new EhsBoardTaskStsInfoDto();//作业活动类任务信息

            //任务信息数据处理
            if (allTaskItems != null && !allTaskItems.isEmpty()) {
                for (EhsTaskItem EhsTaskItem : taskCollect) {
                    updateAllTaskCounts(EhsTaskItem, task);//所有任务信息
                    updateTaskCounts(EhsTaskItem, taskcheck, EhsTaskCategoryTypeEnum.SECURITY_CHECK);//自查类任务信息
                    updateTaskCounts(EhsTaskItem, taskfacility, EhsTaskCategoryTypeEnum.EQUIPMENT_MAINTENANCE);//设备设施类任务信息
                    updateTaskCounts(EhsTaskItem, tasktrouble, EhsTaskCategoryTypeEnum.HIDDEN_DANGER_CONTROL);//隐患治理类任务信息
                    updateTaskCounts(EhsTaskItem, taskinspect, EhsTaskCategoryTypeEnum.INSPECT);//督查类任务信息
                    updateTaskCounts(EhsTaskItem, taskjob, EhsTaskCategoryTypeEnum.JOB_ACTIVITY);//作业活动类任务信息
                }
            }

            //指定部门结果集处理
            EhsBoardDataItemDto ehsBoardDataItemDto = new EhsBoardDataItemDto();
            ehsBoardDataItemDto.setDeptid(id);
            ehsBoardDataItemDto.setName(deptIdAndNames.get(id));
            ehsBoardDataItemDto.setHazard(hazard);//第一类危险源信息
            ehsBoardDataItemDto.setTrouble(trouble);//第二类危险源信息
            ehsBoardDataItemDto.setTroublecorrect(ehsBoardTroubleCorrectStsInfo);//隐患治理统计
            ehsBoardDataItemDto.setTask(task);//全部任务信息统计
            ehsBoardDataItemDto.setTaskcheck(taskcheck);//自查类任务信息
            ehsBoardDataItemDto.setTaskfacility(taskfacility);//设备设施类任务信息
            ehsBoardDataItemDto.setTasktrouble(tasktrouble);//隐患治理类任务信息
            ehsBoardDataItemDto.setTaskinspect(taskinspect);//督查类任务信息
            ehsBoardDataItemDto.setTaskjob(taskjob);//作业活动类任务信息
            result.add(ehsBoardDataItemDto);
        }
        return result;
    }

    /**
     * 根据隐患治理集合获取统计信息
     *
     * @param troubleCorrects: 隐患治理信息集合
     * @author QcCheng Tech
     * @date 2024/12/18
     */
    EhsBoardTroubleCorrectStsInfoDto getTroubleCorrectStatisticsInfo(List<EhsTroubleCorrect> troubleCorrects) {
        EhsBoardTroubleCorrectStsInfoDto troublecorrect = new EhsBoardTroubleCorrectStsInfoDto();
        // 初始化统计变量
        int troubleCorrectsCount = 0, majorEhsCorrectionCount = 0, nodispatchcount = 0, dispatchcount = 0, correctcount = 0, checkcount = 0;

        // 检查 orgAllTroubleCorrects 是否为空
        if (troubleCorrects != null && !troubleCorrects.isEmpty()) {
            // 遍历每个隐患治理对象，进行统计
            for (EhsTroubleCorrect troubleCorrect : troubleCorrects) {
                troubleCorrectsCount++; // 隐患治理数量统计
                if (troubleCorrect.getIsmajor()) majorEhsCorrectionCount++; // 重大危险源统计
                if (troubleCorrect.getHasdispatch()) {
                    //已派单
                    if (troubleCorrect.getHascorrect()) {
                        //已整改完成
                        if (troubleCorrect.getHascheck()) {
                            //已验收通过
                            checkcount++;
                        } else {
                            //已整改完成， 未验收通过
                            correctcount++;
                        }
                    } else {
                        //未整改完成;已派单 整改中
                        dispatchcount++;
                    }
                } else {
                    //未派单
                    nodispatchcount++;
                }
            }
        }

        //设置 DTO 的统计信息
        troublecorrect.setCount(troubleCorrectsCount);
        troublecorrect.setMajorcount(majorEhsCorrectionCount);
        troublecorrect.setNodispatchcount(nodispatchcount);
        troublecorrect.setDispatchcount(dispatchcount);
        troublecorrect.setCorrectcount(correctcount);
        troublecorrect.setCheckcount(checkcount);

        return troublecorrect;
    }

    /**
     * 根据传入的危险源集合统计第一类危险源和第二类危险源的统计数据
     * @param allHazards:危险源
     * @param hazardStsInfo:一类危险源
     * @param troubleStsInfo:二类危险源
     * @author QcCheng Tech
     * @date 2024/12/18
     */
    void getHazardAndTroubleStatisticsInfo(List<EhsHazardInfo> allHazards, EhsBoardHazardStsInfoDto hazardStsInfo, EhsBoardHazardStsInfoDto troubleStsInfo) {
        //1.危险源统计
        //1.1一类危险源统计
        int count = 0, majorcount = 0, bluecount = 0, orangecount = 0, redcount = 0, yellowcount = 0;
        //1.2二类危险源统计
        int count1 = 0, majorcount1 = 0, bluecount1 = 0, orangecount1 = 0, redcount1 = 0, yellowcount1 = 0;
        if (allHazards != null && !allHazards.isEmpty()) {
            for (EhsHazardInfo hazard : allHazards) {
                if (hazard.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HAZARD) {
                    count++;
                    if (hazard.getIsmajor()) majorcount++;//重大危险源统计
                    if (hazard.getRisklevel() != null) {
                        if (hazard.getRisklevel() == EhsRiskLevelEnum.LOW) bluecount++;//蓝色等级数量统计
                        if (hazard.getRisklevel() == EhsRiskLevelEnum.GENERAL) yellowcount++;//黄色等级数量统计
                        if (hazard.getRisklevel() == EhsRiskLevelEnum.GREATER) orangecount++;//橙色等级数量统计
                        if (hazard.getRisklevel() == EhsRiskLevelEnum.MAJOR) redcount++;//红色等级数量统计
                    }
                } else if (hazard.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HIDDEN_TROUBLE) {
                    count1++;
                    if (hazard.getIsmajor()) majorcount1++;
                    if (hazard.getRisklevel() != null) {
                        if (hazard.getRisklevel() == EhsRiskLevelEnum.LOW) bluecount1++;//蓝色等级数量统计
                        if (hazard.getRisklevel() == EhsRiskLevelEnum.GENERAL) yellowcount1++;//黄色等级数量统计
                        if (hazard.getRisklevel() == EhsRiskLevelEnum.GREATER) orangecount1++;//橙色等级数量统计
                        if (hazard.getRisklevel() == EhsRiskLevelEnum.MAJOR) redcount1++;//红色等级数量统计
                    }
                }
            }
            // 设置一类危险源 DTO
            hazardStsInfo.setCount(count);
            hazardStsInfo.setMajorcount(majorcount);
            hazardStsInfo.setBluecount(bluecount);
            hazardStsInfo.setOrangecount(orangecount);
            hazardStsInfo.setRedcount(redcount);
            hazardStsInfo.setYellowcount(yellowcount);

            // 设置二类危险源 DTO
            troubleStsInfo.setCount(count1);
            troubleStsInfo.setMajorcount(majorcount1);
            troubleStsInfo.setBluecount(bluecount1);
            troubleStsInfo.setOrangecount(orangecount1);
            troubleStsInfo.setRedcount(redcount1);
            troubleStsInfo.setYellowcount(yellowcount1);
        }
    }

    /**
     * 任务统计处理
     * @param taskItem:     任务项信息
     * @param taskStsInfo:  任务统计信息
     * @param tasktype:任务类型
     * @author QcCheng Tech
     * @date 2024/12/18
     */
    void updateTaskCounts(EhsTaskItem taskItem, EhsBoardTaskStsInfoDto taskStsInfo, EhsTaskCategoryTypeEnum tasktype) {
        //根据任务类型判断
        if (taskItem.getTasktype() != null) {
            if (taskItem.getTasktype() == tasktype) {
                int taskCount = taskStsInfo.getCount(), finishcount = taskStsInfo.getFinishcount(), timeoutfinishcoun = taskStsInfo.getTimeoutfinishcount();
                taskCount++;
                if (taskItem.getHasfinish()) {
                    //已完成数量统计
                    finishcount++;
                    if (taskItem.getExecendtm() != null && taskItem.getPlanendtm() != null) {
                        //超时完成数量
                        if (taskItem.getPlanendtm().before(taskItem.getExecendtm()))
                            timeoutfinishcoun++;
                    }

                }
                taskStsInfo.setCount(taskCount);
                taskStsInfo.setFinishcount(finishcount);
                taskStsInfo.setTimeoutfinishcount(timeoutfinishcoun);
            }
        }
    }

    /**
     * 全部任务统计处理
     * @param taskItem:    任务项信息
     * @param taskStsInfo: 任务统计信息
     * @author QcCheng Tech
     * @date 2024/12/18
     */
    void updateAllTaskCounts(EhsTaskItem taskItem, EhsBoardTaskStsInfoDto taskStsInfo) {
        int taskCount = taskStsInfo.getCount(), finishcount = taskStsInfo.getFinishcount(), timeoutfinishcoun = taskStsInfo.getTimeoutfinishcount();
        //所有任务数量
        taskCount++;
        taskStsInfo.setCount(taskCount);

        if (taskItem.getHasfinish()) {
            //所有任务已完成数量统计
            finishcount++;
            if (taskItem.getExecendtm() != null && taskItem.getPlanendtm() != null) {
                //所有任务中超时完成数量
                if (taskItem.getPlanendtm().before(taskItem.getExecendtm()))
                    timeoutfinishcoun++;
            }
            taskStsInfo.setFinishcount(finishcount);
            taskStsInfo.setTimeoutfinishcount(timeoutfinishcoun);
        }
    }

    /**
     * 获取单元最新安全状态
     * @param unitId 单元ID
     * @return EhsBoardOrgLatestStatusDTO
     */
    public EhsBoardOrgLatestStatusDTO getUnitLatestStatus(String unitId) throws QCPromptException {
        // 1. 验证单元的有效性
        EhsUnitDto unitDto = unitInfoService.get(unitId);
        if (!Objects.nonNull(unitDto)) {
            throw new QCPromptException("查询的单元信息不存在");
        }

        // 2. 获取单元所有危险源的信息
        List<EhsHazardInfoDto> allUnitHazardDtos = hazardInfoService.getByUnitId(unitId);

        // 3. 转换为Entity并过滤存在的危险源
        List<EhsHazardInfo> allHazards = new ArrayList<>();
        if (allUnitHazardDtos != null && !allUnitHazardDtos.isEmpty()) {
            for (EhsHazardInfoDto dto : allUnitHazardDtos) {
                try {
                    EhsHazardInfo entity = EhsHazardInfoMapper.MAPPER.dtoToEntity(dto);
                    allHazards.add(entity);
                } catch (Exception e) {
                    System.err.println("转换失败: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        }

        // 4. 复用现有统计逻辑
        EhsBoardHazardStsInfoDto hazard = new EhsBoardHazardStsInfoDto();
        EhsBoardHazardStsInfoDto trouble = new EhsBoardHazardStsInfoDto();
        getHazardAndTroubleStatisticsInfo(allHazards, hazard, trouble);

        // 5. 风险评估计算
        int hazardRisk = hazard.getBluecount() * 5 + hazard.getYellowcount() * 10 +
                hazard.getOrangecount() * 20 + hazard.getRedcount() * 40;
        int troubleRisk = trouble.getBluecount() * 5 + trouble.getYellowcount() * 10 +
                trouble.getOrangecount() * 20 + trouble.getRedcount() * 40;

        // 保持与组织查询一致：只使用troubleRisk
        int risk = troubleRisk;
        if (risk > 100) {
            risk = 100;
        }

        // 6. 风险描述
        String description = null;
        if (risk < 20) {
            description = "风险较低，当前状态下无需过多担忧，但仍需保持监控。";
        } else if (risk >= 20 && risk < 40) {
            description = "风险较低，问题较少，建议保持定期检查和预防。";
        } else if (risk >= 40 && risk < 60) {
            description = "风险适中，建议采取适当的防范措施，确保及时解决潜在问题。";
        } else if (risk >= 60 && risk < 80) {
            description = "风险较高，存在一定隐患，需加强监控并立即采取改进措施。";
        } else if (risk >= 80) {
            description = "风险极高，存在重大隐患，必须尽快采取紧急措施进行处理。";
        }

        // 7. 构建返回结果
        EhsBoardOrgLatestStatusDTO result = new EhsBoardOrgLatestStatusDTO();
        result.setRisk(risk);
        result.setHazard(hazard);
        result.setTrouble(trouble);
        result.setDescription(description);

        return result;
    }

    /**
     * 查统计指定时间段内指定单元的安全生产看板数据
     *
     * @param unitid    单元ID
     * @param beginTime 起始时间
     * @param endTime   截止时间
     * @return qc.module.ehs.dto.board.EhsBoardUnitQueryResultDto
     * @author QuCheng Tech
     * @since 2025/6/12
     */
    public EhsBoardUnitQueryResultDto queryStsUnit(String unitid, Date beginTime, Date endTime) throws QCPromptException {
        EhsUnitInfo unit = unitInfoService.getEntity(unitid);
        if (!Objects.nonNull(unit)) {
            throw new QCPromptException("查询的单元不存在");
        }

        //1隐患治理信息统计：根据组织机构和起止时间查询出所有隐患治理信息
        List<EhsTroubleCorrect> orgAllTroubleCorrects = troubleCorrectService.queryUnitTroubleCorrects(unitid, beginTime, endTime);
        //1.1隐患治理信息统计
        EhsBoardTroubleCorrectStsInfoDto troubleCorrectStsInfo = getTroubleCorrectStatisticsInfo(orgAllTroubleCorrects);

        //2任务信息统计：根据组织机构和起止时间查询出所有任务信息
        List<EhsTaskItem> allTaskItems = taskItemService.queryTaskItemEntities(null, unitid, beginTime, endTime, -1, null);
        //2.1任务信息统计：根据组织机构和起止时间查询出所有任务项信息，在根据输入条件中传入的部门信息集合进行过滤筛选得到每个部门的任务统计信息
        EhsBoardTaskStsInfoDto allTaskStsInfo = new EhsBoardTaskStsInfoDto();//所有任务信息
        allTaskStsInfo.setCount(0x0);
        allTaskStsInfo.setFinishcount(0x0);
        allTaskStsInfo.setTimeoutfinishcount(0x0);
        EhsBoardTaskStsInfoDto taskCheckStsInfo = new EhsBoardTaskStsInfoDto();//自查类任务信息
        taskCheckStsInfo.setCount(0x0);
        taskCheckStsInfo.setFinishcount(0x0);
        taskCheckStsInfo.setTimeoutfinishcount(0x0);
        EhsBoardTaskStsInfoDto taskFacilityStsInfo = new EhsBoardTaskStsInfoDto();//设备设施类任务信息
        taskFacilityStsInfo.setCount(0x0);
        taskFacilityStsInfo.setFinishcount(0x0);
        taskFacilityStsInfo.setTimeoutfinishcount(0x0);
        EhsBoardTaskStsInfoDto taskTroubleStsInfo = new EhsBoardTaskStsInfoDto();//隐患治理类任务信息
        taskTroubleStsInfo.setCount(0x0);
        taskTroubleStsInfo.setFinishcount(0x0);
        taskTroubleStsInfo.setTimeoutfinishcount(0x0);
        EhsBoardTaskStsInfoDto taskInspectStsInfo = new EhsBoardTaskStsInfoDto();//督查类任务信息
        taskInspectStsInfo.setCount(0x0);
        taskInspectStsInfo.setFinishcount(0x0);
        taskInspectStsInfo.setTimeoutfinishcount(0x0);
        EhsBoardTaskStsInfoDto taskJobStsInfo = new EhsBoardTaskStsInfoDto();//作业活动类任务信息
        taskJobStsInfo.setCount(0x0);
        taskJobStsInfo.setFinishcount(0x0);
        taskJobStsInfo.setTimeoutfinishcount(0x0);

        if (allTaskItems != null && !allTaskItems.isEmpty()) {
            for (EhsTaskItem taskItem : allTaskItems) {
                updateAllTaskCounts(taskItem, allTaskStsInfo);//所有任务信息
                updateTaskCounts(taskItem, taskCheckStsInfo, EhsTaskCategoryTypeEnum.SECURITY_CHECK);//自查类任务信息
                updateTaskCounts(taskItem, taskFacilityStsInfo, EhsTaskCategoryTypeEnum.EQUIPMENT_MAINTENANCE);//设备设施类任务信息
                updateTaskCounts(taskItem, taskTroubleStsInfo, EhsTaskCategoryTypeEnum.HIDDEN_DANGER_CONTROL);//隐患治理类任务信息
                updateTaskCounts(taskItem, taskInspectStsInfo, EhsTaskCategoryTypeEnum.INSPECT);//督查类任务信息
                updateTaskCounts(taskItem, taskJobStsInfo, EhsTaskCategoryTypeEnum.JOB_ACTIVITY);//作业活动类任务信息
            }
        }

        //3.危险源辨识记录统计：根据组织机构和起止时间查询出所有危险源辨识统计信息
        List<EhsHazardIdentify> orgAllHazardIdentify = ehsHazardIdentifyService.queryUnitHazardIdentifyEntities(unitid, beginTime, endTime);
        //3.1危险源辨识结果数据处理
        int identifyHazardCount = 0, reportTroubleCount = 0;
        if (orgAllHazardIdentify != null && !orgAllHazardIdentify.isEmpty()) {
            for (EhsHazardIdentify hazardIdentify : orgAllHazardIdentify) {
                if (hazardIdentify.getIdentificationresult() != null) {
                    if (hazardIdentify.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HAZARD)
                        identifyHazardCount++;//辨识危险源次数
                    if (hazardIdentify.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HIDDEN_TROUBLE)
                        reportTroubleCount++;//上报上报隐患次数
                }
            }
        }
        EhsBoardHazardIdentifyStsInfoDto identifyStsInfo = new EhsBoardHazardIdentifyStsInfoDto();
        identifyStsInfo.setHazardcount(identifyHazardCount);
        identifyStsInfo.setTroublecount(reportTroubleCount);

        //7.等级评价风险统计：根据组织机构和起止时间查询出所有风险评价信息
        List<EhsHazardRiskEvaluation> hazardRiskEvaluations = ehsHazardRiskevlService.queryUnitRiskevlEntities(unitid, beginTime, endTime);
        //7.1等级评价风险结果统计
        int riskEvaluationCount = 0, blueCount = 0, yellowCount = 0, orangeCount = 0, redCount = 0;
        if (hazardRiskEvaluations != null && !hazardRiskEvaluations.isEmpty()) {
            for (EhsHazardRiskEvaluation hazardRiskEvaluation : hazardRiskEvaluations) {
                riskEvaluationCount++;//总次数
                if (hazardRiskEvaluation.getRisklevel() != null) {
                    if (hazardRiskEvaluation.getRisklevel() == EhsRiskLevelEnum.LOW) blueCount++;//蓝色等级数量统计
                    if (hazardRiskEvaluation.getRisklevel() == EhsRiskLevelEnum.GENERAL) yellowCount++;//黄色等级数量统计
                    if (hazardRiskEvaluation.getRisklevel() == EhsRiskLevelEnum.GREATER) orangeCount++;//橙色等级数量统计
                    if (hazardRiskEvaluation.getRisklevel() == EhsRiskLevelEnum.MAJOR) redCount++;//红色等级数量统计
                }

            }
        }
        EhsBoardRiskEvaluationStsInfoDto riskEvaluationStsInfo = new EhsBoardRiskEvaluationStsInfoDto();
        riskEvaluationStsInfo.setCount(riskEvaluationCount);
        riskEvaluationStsInfo.setBluecount(blueCount);
        riskEvaluationStsInfo.setYellowcount(yellowCount);
        riskEvaluationStsInfo.setOrangecount(orangeCount);
        riskEvaluationStsInfo.setRedcount(redCount);

        //6.安全事故统计：根据组织机构和起止时间查询出所有安全事故统计信息
        List<EhsAccidentRecord> allAccidentRecords = ehsAccidentRecordService.queryAccidentRecordEntities(null, unitid, beginTime, endTime);
        //6.1安全事故结果统计
        int accidentCount = 0, majorCount = 0, injurednum = 0, deathnum = 0;
        Double ecoloss = 0.0;
        if (allAccidentRecords != null && !allAccidentRecords.isEmpty()) {
            for (EhsAccidentRecord accidentRecord : allAccidentRecords) {
                accidentCount++;//次数
                injurednum += accidentRecord.getInjurednum();//重伤人数
                deathnum += accidentRecord.getDeathnum();//重大事故次数
                ecoloss += accidentRecord.getEcoloss();//直接经济损失
                if (accidentRecord.getLvl() == EhsAccidentLevelEnum.MAJOR || accidentRecord.getLvl() == EhsAccidentLevelEnum.ESPECIALLY_MAJOR)
                    majorCount++;//重大事故次数
            }
        }
        EhsBoardAccidentStsInfoDto accidentStsInfo = new EhsBoardAccidentStsInfoDto();
        accidentStsInfo.setCount(accidentCount);
        accidentStsInfo.setMajorcount(majorCount);
        accidentStsInfo.setDeathnum(deathnum);
        accidentStsInfo.setInjurednum(injurednum);
        accidentStsInfo.setEcoloss(ecoloss);

        //返回结果集
        EhsBoardUnitQueryResultDto result = new EhsBoardUnitQueryResultDto();
        result.setTroublecorrect(troubleCorrectStsInfo);//隐患治理统计结果
        result.setTask(allTaskStsInfo);//所有任务信息统计结果
        result.setTaskcheck(taskCheckStsInfo);//自查类任务信息统计结果
        result.setTaskfacility(taskFacilityStsInfo);//隐患治理类任务信息统计结果
        result.setTasktrouble(taskTroubleStsInfo);//隐患治理类任务信息统计结果
        result.setTaskinspect(taskInspectStsInfo);//督查类任务信息统计结果
        result.setTaskjob(taskJobStsInfo);//作业活动类任务信息统计结果
        result.setIdentify(identifyStsInfo);//危险源辨识统计结果
        result.setRiskevl(riskEvaluationStsInfo);//风险评价统计结果
        result.setAccident(accidentStsInfo);//事故统计统计结果

        return result;
    }

    /**
     * 获取组织各单元的危险源看板数据
     * 统计组织中各单元的危险源（可以指定第一类或第二类）统计数量；
     * 每个单元统计数量包含：总数、一般/重大数量、各风险等级数量；
     *
     * @param orgcode 组织代码
     * @param flag    一类=1，第二类=2，全部=其他，小于1表示无效
     * @return java.util.List<qc.module.ehs.dto.board.EhsBoardOrgUnitHazardsQueryResultItemDto>
     * @author QuCheng Tech
     * @since 2025/6/10
     */
    public List<EhsBoardOrgUnitHazardsQueryResultItemDto> getOrgUnitHazards(String orgcode, int flag) throws QCPromptException {
        if (StringUtils.isBlank(orgcode))
            throw new QCPromptException("统计组织各单元的危险源看板数据查询条件中组织代码不能为空");

        //查询单元集合，最终返回结果根据单元遍历得到（可能在危险源集合中部分单元没有危险源信息）
        List<EhsUnitDto> units = unitInfoService.getUnitByOrgCode(orgcode);
        if (units != null && units.size() > 0x0) {
            //初始化返回结果
            List<EhsBoardOrgUnitHazardsQueryResultItemDto> result = new ArrayList<>();

            //查询组织的危险源信息集合
            List<EhsHazardInfo> allHazards = hazardInfoService.getOrgAllExistHazards(orgcode, flag);
            //遍历单元获取对应单元中的危险源和隐患信息进行统计
            for (EhsUnitDto unit : units) {
                String unitid = unit.getUnitid();
                String unitname = unit.getUnitname();

                //单元的危险源统计数据初始化赋值
                EhsBoardOrgUnitHazardsQueryResultItemDto item = new EhsBoardOrgUnitHazardsQueryResultItemDto();
                item.setUnitid(unitid);
                item.setUnitname(unitname);

                EhsBoardHazardStsInfoDto hazard = new EhsBoardHazardStsInfoDto();
                hazard.setCount(0x0);
                hazard.setMajorcount(0x0);
                hazard.setBluecount(0x0);
                hazard.setYellowcount(0x0);
                hazard.setOrangecount(0x0);
                hazard.setRedcount(0x0);
                EhsBoardHazardStsInfoDto trouble = new EhsBoardHazardStsInfoDto();
                trouble.setCount(0x0);
                trouble.setMajorcount(0x0);
                trouble.setBluecount(0x0);
                trouble.setYellowcount(0x0);
                trouble.setOrangecount(0x0);
                trouble.setRedcount(0x0);

                if (allHazards != null && allHazards.size() > 0x0) {
                    //筛选第一类危险源
                    List<EhsHazardInfo> unitHazards = allHazards.stream().filter(p -> p.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HAZARD && StringUtils.equalsIgnoreCase(p.getUnitid(), unitid)).collect(Collectors.toList());
                    if (unitHazards != null && unitHazards.size() > 0x0) {
                        hazard.setCount(unitHazards.size());
                        hazard.setMajorcount((int) unitHazards.stream().filter(p -> p.getIsmajor() == true).count());
                        hazard.setBluecount((int) unitHazards.stream().filter(p -> p.getRisklevel() == EhsRiskLevelEnum.LOW).count());
                        hazard.setYellowcount((int) unitHazards.stream().filter(p -> p.getRisklevel() == EhsRiskLevelEnum.GENERAL).count());
                        hazard.setOrangecount((int) unitHazards.stream().filter(p -> p.getRisklevel() == EhsRiskLevelEnum.GREATER).count());
                        hazard.setRedcount((int) unitHazards.stream().filter(p -> p.getRisklevel() == EhsRiskLevelEnum.MAJOR).count());
                    }

                    //筛选第二类危险源
                    List<EhsHazardInfo> unitTroubles = allHazards.stream().filter(p -> p.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HIDDEN_TROUBLE && StringUtils.equalsIgnoreCase(p.getUnitid(), unitid)).collect(Collectors.toList());
                    if (unitTroubles != null && unitTroubles.size() > 0x0) {
                        trouble.setCount(unitTroubles.size());
                        trouble.setMajorcount((int) unitTroubles.stream().filter(p -> p.getIsmajor() == true).count());
                        trouble.setBluecount((int) unitTroubles.stream().filter(p -> p.getRisklevel() == EhsRiskLevelEnum.LOW).count());
                        trouble.setYellowcount((int) unitTroubles.stream().filter(p -> p.getRisklevel() == EhsRiskLevelEnum.GENERAL).count());
                        trouble.setOrangecount((int) unitTroubles.stream().filter(p -> p.getRisklevel() == EhsRiskLevelEnum.GREATER).count());
                        trouble.setRedcount((int) unitTroubles.stream().filter(p -> p.getRisklevel() == EhsRiskLevelEnum.MAJOR).count());
                    }
                }

                item.setHazard(hazard);
                item.setTrouble(trouble);

                result.add(item);
            }

            return result;
        }

        return null;
    }

    /**
     * 统计组织中各单元的任务数量
     *
     * @param orgcode           组织代码
     * @param beginTime         起始时间
     * @param endTime           截止时间
     * @param taskCategoryTypes 任务大类集合
     * @return java.util.List<qc.module.ehs.dto.board.EhsBoardTaskQueryResultItemDto>
     * @author QuCheng Tech
     * @since 2025/6/13
     */
    public List<EhsBoardTaskQueryResultItemDto> stsOrgUnitTasks(String orgcode, Date beginTime, Date endTime, List<EhsTaskCategoryTypeEnum> taskCategoryTypes) throws QCPromptException {
        List<EhsTaskItem> taskItems = taskItemService.queryTaskItemEntities(orgcode, null, beginTime, endTime, -1, taskCategoryTypes);
        if (taskItems != null) {
            //从任务项集合中筛选出所有的单元ID
            List<String> unitIds = taskItems.stream().map(p -> p.getUnitid()).distinct().collect(Collectors.toList());
            if (unitIds != null && unitIds.size() > 0x0) {
                List<EhsBoardTaskQueryResultItemDto> result = new ArrayList<>();

                for (String unitid : unitIds) {
                    EhsBoardTaskQueryResultItemDto item = new EhsBoardTaskQueryResultItemDto();
                    item.setUnitid(unitid);

                    EhsBoardTaskStsInfoDto task = new EhsBoardTaskStsInfoDto();
                    task.setCount(0x0);
                    task.setFinishcount(0x0);
                    task.setTimeoutfinishcount(0x0);
                    EhsBoardTaskStsInfoDto taskcheck = new EhsBoardTaskStsInfoDto();
                    taskcheck.setCount(0x0);
                    taskcheck.setFinishcount(0x0);
                    taskcheck.setTimeoutfinishcount(0x0);
                    EhsBoardTaskStsInfoDto taskfacility = new EhsBoardTaskStsInfoDto();
                    taskfacility.setCount(0x0);
                    taskfacility.setFinishcount(0x0);
                    taskfacility.setTimeoutfinishcount(0x0);
                    EhsBoardTaskStsInfoDto taskinspect = new EhsBoardTaskStsInfoDto();
                    taskinspect.setCount(0x0);
                    taskinspect.setFinishcount(0x0);
                    taskinspect.setTimeoutfinishcount(0x0);
                    EhsBoardTaskStsInfoDto taskjob = new EhsBoardTaskStsInfoDto();
                    taskjob.setCount(0x0);
                    taskjob.setFinishcount(0x0);
                    taskjob.setTimeoutfinishcount(0x0);
                    EhsBoardTaskStsInfoDto tasktrouble = new EhsBoardTaskStsInfoDto();
                    tasktrouble.setCount(0x0);
                    tasktrouble.setFinishcount(0x0);
                    tasktrouble.setTimeoutfinishcount(0x0);

                    //筛选出当前单元的任务项集合
                    List<EhsTaskItem> unitTaskItems = taskItems.stream().filter(p -> StringUtils.equalsIgnoreCase(p.getUnitid(), unitid)).collect(Collectors.toList());
                    if (unitTaskItems != null && unitTaskItems.size() > 0x0) {
                        for (EhsTaskItem taskItem : unitTaskItems) {
                            updateAllTaskCounts(taskItem, task);//所有任务信息
                            updateTaskCounts(taskItem, taskcheck, EhsTaskCategoryTypeEnum.SECURITY_CHECK);//自查类任务信息
                            updateTaskCounts(taskItem, taskfacility, EhsTaskCategoryTypeEnum.EQUIPMENT_MAINTENANCE);//设备设施类任务信息
                            updateTaskCounts(taskItem, tasktrouble, EhsTaskCategoryTypeEnum.HIDDEN_DANGER_CONTROL);//隐患治理类任务信息
                            updateTaskCounts(taskItem, taskinspect, EhsTaskCategoryTypeEnum.INSPECT);//督查类任务信息
                            updateTaskCounts(taskItem, taskjob, EhsTaskCategoryTypeEnum.JOB_ACTIVITY);//作业活动类任务信息
                        }
                    }

                    item.setTask(task);
                    item.setTaskcheck(taskcheck);
                    item.setTaskfacility(taskfacility);
                    item.setTaskinspect(taskinspect);
                    item.setTaskjob(taskjob);
                    item.setTasktrouble(tasktrouble);

                    result.add(item);
                }

                return result;
            }
        }

        return null;
    }
}
